package edu.upb.acs.jobsmaps.database;

import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import edu.upb.acs.jobsmaps.entity.Company;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

/**
 * Created by dani on 5/25/2014.
 */
public class HttpRequestHandler {

	private static final String TAG = HttpRequestHandler.class.getName();
	// function get json from url
	// by making HTTP POST or GET mehtod
	public static String makeHttpRequest(String url, String method,
								  List<NameValuePair> params) {

		// Making HTTP request
		try {

			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpParams httpParams = httpClient.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);

			HttpResponse httpResponse = null;
			String responseValue = null;
			// check for request method
			if (method == "POST") {
				HttpPost httpPost = new HttpPost(url);
				if (null != params && params.size() > 0) {
					httpPost.setEntity(new UrlEncodedFormEntity(params));
				}
				httpResponse = httpClient.execute(httpPost);
			} else if (method == "GET") {
				if (null != params && params.size() > 0) {
					Log.d(TAG, "parameters = " + params);
					String paramString = URLEncodedUtils.format(params, "utf-8");
					url += "?" + paramString;
					Log.d(TAG, "url = " + url);

				} else {
					Log.d(TAG, "Null parameters");
				}
				HttpGet httpGet = new HttpGet(url);

				httpResponse = httpClient.execute(httpGet);
			} else {
				Log.e(TAG, "Unsupported method");
				return null;
			}

			responseValue = EntityUtils.toString(httpResponse.getEntity());
			Log.d(TAG, "Response body = " + responseValue);

			return responseValue;
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "Can not execute request", e);
			throw new RuntimeException(e);
		} catch (ClientProtocolException e) {
			Log.e(TAG, "Can not execute request", e);
			throw new RuntimeException(e);
		} catch (IOException e) {
			Log.e(TAG, "Can not execute request", e);
			throw new RuntimeException(e);
		}
	}
}
